package com.gusti.admincasa.services.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gusti.admincasa.dao.ITimeRegisterDao;
import com.gusti.admincasa.dao.IUserDao;
import com.gusti.admincasa.model.TimeRegister;
import com.gusti.admincasa.model.User;
import com.gusti.admincasa.services.IFilterService;
import com.gusti.admincasa.util.UserData;
import com.gusti.admincasa.util.DateUtil;
import com.gusti.admincasa.util.Debug;

/**
 * 
 * @author gusti
 *
 */
@Service
public class FilterService implements IFilterService {

	@Autowired
	ITimeRegisterDao timeRegisterDao;
	@Autowired
	IUserDao userDao;

	private Map<String, UserData> usersMap = new HashMap<String, UserData>();

	@Transactional
	public void filterData( int timeout ) {
		long timeStamp = new Date().getTime();
		TimeRegister timeRegister = new TimeRegister();
		User user = new User();

		for ( Map.Entry<String, UserData> entry : this.usersMap.entrySet() ) {
			String uuid = (String)entry.getKey();
			UserData data = (UserData)entry.getValue();
			if( timeStamp - Long.parseLong( data.getTimeStamp() ) > timeout ) {
				Debug.log( data.getUserName() + " is offline" );
				this.usersMap.remove( uuid );

				//busco timeregister
				timeRegister = timeRegisterDao.findTimeRegister( data.getUuid() );
				timeRegister.setEndDate( DateUtil.createDateTime() );
				timeRegisterDao.update( timeRegister );

				//busco usuario
				user = userDao.findUser( data.getUserName() );
				user.setStatus( User.OFFLINE_STATUS );
				userDao.update( user );
			}
		}
	}

	public void putUser( UserData data ) {
		if( !usersMap.containsKey( data.getUuid() ) ) {
			Debug.log( data.getUserName() + " is online" );
		}
		this.usersMap.put( data.getUuid(), data );
	}

}
